package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkAddressListByProto;
import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;

/**
* @description: 通讯录
* @author TAO
* @date 2019/6/20 11:46
*/

@ClientEvent("AddressList")
public class AddressListHandler extends OpenMessageHandler implements RedisService {

    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.info("------------------------通讯录AddressList------------------------------");
        ImtalkAddressListByProto.AddressListRes.Builder res=ImtalkAddressListByProto.AddressListRes.newBuilder();
        try{
            ImtalkAddressListByProto.AddressListReq req=ImtalkAddressListByProto.AddressListReq.parseFrom(protobuf);
            res.setSign(req.getSign());//返回前端标识信息

            //获取好友列表
            Map<String, String> friendList= R_FRIEND.hgetAll(userId);

            int count=0;

            for (String key: friendList.keySet()){
                JSONObject jsonObject2=JSONObject.parseObject(friendList.get(key));
                jsonObject2.put("userId",key);
                res.addFriendList(String.valueOf(jsonObject2));
                count++;
            }

           //获取保存的群聊
           List<String> groupList=R_USER_R_GROUP.lrangeAll(userId);

           Out.debug("当前用户"+userId+"保存的群聊"+groupList);

           for (int i=0;i<groupList.size();i++){
               Out.debug("----------搜索保存的群聊-------------------"+groupList.get(i));
               res.addGroupList(String.valueOf(groupList.get(i)));
           }

            Out.debug("好友列表"+friendList);
            Out.debug("好友列表res"+res.getFriendListList());
            Out.debug("保存群列表"+groupList);
            Out.debug("保存群列表res"+res.getGroupListList());

            //返回消息
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        }catch (InvalidProtocolBufferException e){
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }
}
